package com.zh.media.utils;


import android.os.Build;

import androidx.annotation.RequiresApi;

import android.util.Base64;
import android.util.Log;

import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
/**
 * @Description:  rsa加密
 * @Author:         mark
 * @CreateDate:     2024/12/7 17:15
 * @UpdateUser:     更新者：
 * @UpdateDate:     2024/12/7 17:15
 * @UpdateRemark:   更新说明：
 * @Version:        1.0
 */
public class DevClient {
   private static String publicKeyBase64 = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArNFjgw45e/heWyvfxGvYbZtvppFnPiD7fHPM3MQ77mTfyp7xdI/XYJY6WDd+dCHB3ry/mgvyrH3njntiJZOyAcRBJQ7/xOup2Uiw8fZltAdlDAz19BZgJlZqQNSalxmUbmKgdOSnOVRSeSckAoTWdj4Ykqp+k09hhYxYEVqmfPKjA/Mu2GT59hx8ThynDZzS5U0/tK11evuPw5cjLRLK0bGviTegZNj41yatHXmGdzjuJVODRsaYiqgENoYt4l6dmNmrWIDvpGqVsROighMHHslsQEN6eoO5AB7A+Y6JcqXMWBNChMDUGWoxqsg6gROeMkAKESInx3Qr9pg0JldIfQIDAQAB";

    public static String encryptWithPublicKey(String text) {
        try {
            // 将Base64编码的公钥字符串转换为字节数组
            byte[] publicKeyBytes = Base64.decode(publicKeyBase64, Base64.DEFAULT);
            // 将公钥字节数组转换为Key对象
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PublicKey publicKey = keyFactory.generatePublic(keySpec);

            // 使用公钥对数据进行加密
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] encryptedBytes = cipher.doFinal(text.getBytes());

            // 将加密后的数据转换为Base64编码的字符串
            return Base64.encodeToString(encryptedBytes, Base64.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    public static byte[] encryptData(String text) {
        try {
            // 将Base64编码的公钥字符串转换为字节数组
            byte[] publicKeyBytes = Base64.decode(publicKeyBase64, Base64.DEFAULT);
            // 将公钥字节数组转换为Key对象
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PublicKey publicKey = keyFactory.generatePublic(keySpec);

            // 使用公钥对数据进行加密
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] encryptedBytes = cipher.doFinal(text.getBytes());


            // 将加密后的数据转换为Base64编码的字符串
            return encryptedBytes;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


}

